package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper logsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     * 返回值： 任务的id
     * 参数：自媒体端传递过来的任务
     *
     * @param task
     */
    @Override
    public long addTask(Task task) {
        //1. 把任务添加到数据库-添加2张表
       Boolean status = addDataToDB(task);

        //2. 添加任务到redis
        if(status){
            addDataToRedis(task);
        }

        //3. 返回任务的id

        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        //1. 删除数据
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
        //2. 删除redis中的数据
        if(null != task){
            removeTaskFromCache(task);
            flag = true;
        }

        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key = type + "_" + priority;
        Task task = null;

        String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if(StringUtils.isNotEmpty(json)){
            task = JSON.parseObject(json, Task.class);

            updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
        }

        return task;
    }

    /**
     * 删除redis中的数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        //执行时间小于等于当前时间-删除list集合中的数据否则删除zset
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC + key,0, JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务数据库中的数据
     * @param taskId
     * @return
     */
    private Task updateDb(long taskId, int status) {
        //1. 删除任务本身
        taskinfoMapper.deleteById(taskId);

        //2. 更新任务的状态
        TaskinfoLogs logs = logsMapper.selectById(taskId);
        logs.setStatus(status);

        logsMapper.updateById(logs);
        Task task = new Task();
        BeanUtils.copyProperties(logs, task);
        task.setExecuteTime(logs.getExecuteTime().getTime());

        return task;

    }

    /**
     * 添加数据到redis
     * @param task
     */
    private void addDataToRedis(Task task) {
        //1. 获取当前时间和未来五分钟的时间
        long currentTimeMillis = System.currentTimeMillis();

        //获取未来五分钟的时间
        Calendar calendar = Calendar.getInstance(); // 初始化一个日志对象
        calendar.add(Calendar.MINUTE, 5); // 在当前时间添加5分钟
        long futureTime = calendar.getTimeInMillis();

        //2. 判断任务执行的时间-如果是立即执行的添加到list 如果是未来五分钟执行的添加到zset 其他数据不处理
        if(task.getExecuteTime() <= currentTimeMillis){
            //如果是立即执行的添加到list
            String key = ScheduleConstants.TOPIC + task.getTaskType() + "_" + task.getPriority();
            cacheService.lLeftPush(key, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= futureTime){
            String key = ScheduleConstants.FUTURE + task.getTaskType() + "_" + task.getPriority();
            cacheService.zAdd(key, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    /**
     * 添加任务到数据库表
     * @param task
     * @return
     */
    private Boolean addDataToDB(Task task) {
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);

        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));

        int count = taskinfoMapper.insert(taskinfo);

        TaskinfoLogs logs = new TaskinfoLogs();
        BeanUtils.copyProperties(task, logs);
        logs.setStatus(ScheduleConstants.SCHEDULED);
        logs.setVersion(1);
        logs.setTaskId(taskinfo.getTaskId());
        logs.setExecuteTime(new Date(task.getExecuteTime()));

        int count1 = logsMapper.insert(logs);

        //一定要给task赋值id否则返回结果就是空的
        task.setTaskId(taskinfo.getTaskId());

        return count == 1 && count1 == 1;
    }

    /**
     * 定时的刷新zset中的数据到list集合中
     */

    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

        if(StringUtils.isNotEmpty(token)){
            log.info("refresh invoked.........");

            //1. 获取zset中所有的key
            Set<String> futureSet = cacheService.scan("future_*");

            /**
             * futureSet:
             *  future_1_1, future_1_2, future_2_2,future_2_1
             */
            //2. 判断这些key里面的数据是否有过期的
            if(null != futureSet && futureSet.size() > 0){
                for (String futureKey : futureSet) { //future_1_1  task1 task2 task3 ...
                    Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                    if(null != tasks && tasks.size() > 0){
                        String topicKey = ScheduleConstants.TOPIC + futureKey.substring(futureKey.indexOf("future_"));
                        //3. 如果有过期的则删除同时把数据添加到list集合
                        cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    }
                }
            }

            cacheService.relaseLock("FUTURE_TASK_SYNC");
        }
    }


    @PostConstruct // 对象一点被创建就会调用reloadData来完成对象的初始化操作
    @Scheduled(cron = "0 */1 * * * ?")
    public void reloadData(){
        log.info("reloadData invoked.........");
        //1. 删除redis中的所有的缓存数据
        clearCache();

        //2. 查询执行时间小于未来5分钟的所有的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));

        //3. 遍历任务并把任务添加到redis
        if(null != taskinfoList && taskinfoList.size() > 0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);

                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addDataToRedis(task);
            }
        }

    }

    /**
     * 清除缓存数据
     */
    private void clearCache() {
        Set<String> topicSet = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureSet = cacheService.scan(ScheduleConstants.FUTURE + "*");

        cacheService.delete(topicSet);
        cacheService.delete(futureSet);
    }
}
